#include "BusinessTask.hpp"
#include "logger.h"
namespace wd{


UserLoginSection1::UserLoginSection1(wd::Packet & packet, wd::TcpConnectionptr tcpconn)
:_packet(packet)
,_tcpconn(tcpconn){

}

void UserLoginSection1::process(){
        printf("in loginSection1::process\n");
        if(_packet.type == wd::TASK_LOGIN_SECTION1){
            string username = _packet.msg;
            //此处要确保username末尾没有 \n
            if(username.back()=='\n'){
                username.pop_back();
            }
            printf("username:__%s__\n",username.c_str());
            struct spwd * sp;
            sp = getspnam(username.c_str());
            if(sp == nullptr){
                printf("sp is nullptr\n");
                //用户名出错，将信息告知用户
               //LogDebug("getspnam error");
                //LOG_DEBUG("getspnam error");
               wd::TLV tlv;
               tlv.type = wd::TASK_LOGIN_SECTION1_RESP_ERROR;
               tlv.length = 0;
               _tcpconn->sendInLoop(tlv);
               return;
            }
            printf("username is existed\n");
            //用户名验证成功，将setting(含盐值)发给用户
            _tcpconn->set_pwdp(sp->sp_pwdp); //以便密码验证时可以取出 
            string setting;
            get_setting(setting, sp->sp_pwdp);
            printf("setting: %s\n",setting.c_str());
            printf("sp_pwdp:%s\n",sp->sp_pwdp);
            //构造TLV，将setting发给用户
            wd::TLV tlv;
            memset(&tlv,0,sizeof(tlv));
            tlv.type = wd::TASK_LOGIN_SECTION1_RESP_OK;
            tlv.length = setting.size();
            strncpy(tlv.data,setting.c_str(),tlv.length);
            _tcpconn->sendInLoop(tlv);
        }
    }

void UserLoginSection1::get_setting(string & setting, char * passwd){
        int i,j;
        for(i=0, j=0; passwd[i] && j!= 4; ++i){
            if(passwd[i] == '$'){
                ++j;
            }
        }
        char buff[128] = {0};
        strncpy(buff,passwd,i-1);
        setting.assign(buff,i);

}


UserLoginSection2::UserLoginSection2(wd::Packet & packet, wd::TcpConnectionptr tcpconn)
:_packet(packet)
,_tcpconn(tcpconn){

}

void UserLoginSection2::process(){
    printf("in loginSection2::process\n");
    if(_packet.type == wd::TASK_LOGIN_SECTION2){
        string encoded = _packet.msg; //用户发来的密文
        string true_secret = _tcpconn->get_pwdp();
        if(encoded == true_secret){
            //验证成功
            LOG_DEBUG("log success!");
            wd::TLV tlv;
            memset(&tlv,0,sizeof(tlv));
            tlv.type = wd::TASK_LOGIN_SECTION2_RESP_OK;
            tlv.length = 0;
            _tcpconn->sendInLoop(tlv);
        }else{
            wd::TLV tlv;
            memset(&tlv,0,sizeof(tlv));
            tlv.type = wd::TASK_LOGIN_SECTION2_RESP_ERROR;
            tlv.length = 0;
            _tcpconn->sendInLoop(tlv);
        }
    }

}





}
